package rs.belex.belexdroid.services.impl.ksoap2;

import java.util.LinkedList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;

import rs.belex.belexdroid.beans.AccountBean;
import rs.belex.belexdroid.beans.ShareBean;
import rs.belex.belexdroid.beans.UserBean;
import rs.belex.belexdroid.beans.interfaces.Account;
import rs.belex.belexdroid.beans.interfaces.Share;
import rs.belex.belexdroid.beans.interfaces.User;
import rs.belex.belexdroid.services.interfaces.ILogin;
import android.util.Log;

public class LoginKsoap2Impl extends ServiceClientKsoap2Impl implements ILogin {
	private static String TAG = LoginKsoap2Impl.class.getSimpleName();

	public LoginKsoap2Impl() {
	};

	public User login(String username, String password) {

		User user = null;
		Log.d(TAG, "login called");
		final String SOAP_ACTION = "";
		final String METHOD_NAME = "login";

		// Creating input parameters
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		request.addProperty("username", username);
		request.addProperty("password", password);

		SoapObject response = (SoapObject) super.requestComplexType(request,
				SOAP_ACTION);

		if (response != null) {
			// Parsing response to User type
			try {
				user = new UserBean();
				user.setName(response.getProperty("name").toString());
				user.setUsername(response.getProperty("username").toString());
				user.setPassword(response.getProperty("password").toString());
				// array of complex types needs to be parsed
				user.setAccount(getAccountFromResponse((SoapObject) response
						.getProperty("account")));
				Log.d(TAG, "User created successfully");
			} catch (Exception e) {
				Log.e(TAG,
						"Error while parsing response to User type of Object");
				e.printStackTrace();
			}

			Log.d(TAG, "Logged in.");
		}
		return user;

	}

	Account getAccountFromResponse(SoapObject accountResponse) {

		SoapObject sharesResponse = (SoapObject) accountResponse
				.getProperty("shares");

		int propsNum = sharesResponse.getPropertyCount();
		List<Share> shares = new LinkedList<Share>();
		// Iterate through properties and make an array
		for (int i = 0; i < propsNum; i++) {
			SoapObject element = (SoapObject) sharesResponse.getProperty(i);
			Share share = new ShareBean();
			share.setName(element.getProperty("name").toString());
			share.setType(element.getProperty("type").toString());
			share.setSymbol(element.getProperty("symbol").toString());
			share.setValue(new Double(element.getProperty("value").toString()));
			shares.add(share);
		}
		return new AccountBean(shares);
	}

}
